using LiJ.Http.Mos;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace LiJ.Http.Extention
{
	/// <summary>
	/// http请求辅助类
	/// </summary>
	public static class RestExtention
	{
		private static HttpClient _client;

		/// <summary>
		/// 同步的请求方式
		/// </summary>
		/// <param name="request">请求的参数</param>
		/// <param name="client"></param>
		/// <returns>自定义的Response结果</returns>
		public static Task<HttpResponseMessage> RestSend(this LHttpRequest request, HttpClient client = null)
		{
			return request.RestSend(HttpCompletionOption.ResponseContentRead, CancellationToken.None, client);
		}

		/// <summary>
		/// 同步的请求方式
		/// </summary>
		/// <param name="request">请求的参数</param>
		/// <param name="completionOption"></param>
		/// <param name="client"></param>
		/// <returns>自定义的Response结果</returns>
		public static Task<HttpResponseMessage> RestSend(this LHttpRequest request, HttpCompletionOption completionOption, HttpClient client = null)
		{
			return request.RestSend(completionOption, CancellationToken.None, client);
		}

		/// <summary>
		/// 同步的请求方式
		/// </summary>
		/// <param name="request">请求的参数</param>
		/// <param name="completionOption"></param>
		/// <param name="token"></param>
		/// <param name="client"></param>
		/// <returns>自定义的Response结果</returns>
		public static Task<HttpResponseMessage> RestSend(this LHttpRequest request, HttpCompletionOption completionOption, CancellationToken token, HttpClient client = null)
		{
			return (client ?? GetDefaultClient()).RestSend(request, completionOption, token);
		}

		/// <summary>
		/// 配置请求处理类
		/// </summary>
		/// <returns></returns>
		private static HttpClient GetDefaultClient()
		{
			if (_client != null)
			{
				return _client;
			}
			return _client = new HttpClient();
		}
	}
}
